package Classic150;

import Tree.TreeNode;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class 二叉树的层序遍历 {

    List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> levelOrder(TreeNode root) {
        /*
            递归
         */
        levelOrderRecursion(root, 0);
        return res;

        /*
           迭代
         */
        /*if (root == null) return res;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            List<Integer> list = new ArrayList<>();
            int size = queue.size();
            while (size-- > 0) {
                TreeNode node = queue.poll();
                list.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            res.add(list);
        }
        return res;*/
    }

    private void levelOrderRecursion(TreeNode node, int deep) {
        if (node == null) return;
        deep++;
        if (res.size() < deep) res.add(new ArrayList<>());
        res.get(deep - 1).add(node.val);
        levelOrderRecursion(node.left, deep);
        levelOrderRecursion(node.right, deep);
    }
}
